<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>用户管理 - 医生管理系统</title>
  <!-- 引入Vue3 -->
  <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
  <!-- 引入Element Plus -->
  <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
  <script src="https://unpkg.com/element-plus"></script>
  <!-- 引入Axios -->
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <!-- 引入Font Awesome -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

  <style>
    .page-container {
      padding: 20px;
      background-color: #f5f7fa;
      min-height: 100vh;
    }
    .header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      padding: 20px;
      background: white;
      border-radius: 8px;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
    .search-form {
      background: white;
      padding: 20px;
      margin-bottom: 20px;
      border-radius: 8px;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
    .table-container {
      background: white;
      padding: 20px;
      border-radius: 8px;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
    .user-avatar {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      background: #409eff;
      color: white;
      display: flex;
      align-items: center;
      justify-content: center;
      font-weight: bold;
    }
    .status-active {
      color: #67c23a;
    }
    .status-inactive {
      color: #909399;
    }
    .mr-1 {
      margin-right: 4px;
    }
  </style>
</head>
<body>
<div id="app">
  <div class="page-container">
    <!-- 头部 -->
    <div class="header">
      <h1 style="margin: 0; color: #303133;">用户管理</h1>
      <div>
        <el-button type="primary" @click="handleAdd">
        </el-button>
        <el-button @click="handleRefresh">
          <i class="fas fa-refresh mr-1"></i> 刷新
        </el-button>
      </div>
    </div>

    <!-- 编辑用户弹窗 -->
    <el-dialog
            v-model="dialogVisible"
            title="编辑用户"
            width="500px"
            :before-close="handleDialogClose"
    >
      <el-form
              :model="editForm"
              ref="editFormRef"
              label-width="100px"
              :rules="editRules"
      >
        <el-form-item label="用户姓名" prop="name">
          <el-input
                  v-model="editForm.name"
                  placeholder="请输入用户姓名"
                  maxlength="20"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input
                  v-model="editForm.phone"
                  placeholder="请输入手机号"
                  maxlength="20"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
                  v-model="editForm.email"
                  placeholder="请输入邮箱（可选）"
                  maxlength="40"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select
                  v-model="editForm.role"
                  placeholder="请选择角色"
          >
            <el-option label="医生" value="doctor"></el-option>
            <el-option label="管理员" value="admin"></el-option>
            <el-option label="患者" value="patient"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="账号状态" prop="status">
          <el-select
                  v-model="editForm.status"
                  placeholder="请选择状态"
          >
            <el-option label="启用" :value="1"></el-option>
            <el-option label="禁用" :value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUpdateSubmit">确定更新</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :model="searchForm" inline>
        <el-form-item label="关键词">
          <el-input
                  v-model="searchForm.keyword"
                  placeholder="请输入用户名、手机号或邮箱"
                  clearable
                  style="width: 240px"
                  @keyup.enter="handleSearch"
          >
            <template #prefix>
              <i class="fas fa-search"></i>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="角色">
          <el-select
                  v-model="searchForm.role"
                  placeholder="请选择角色"
                  clearable
                  style="width: 140px"
          >
            <el-option label="医生" value="doctor"></el-option>
            <el-option label="管理员" value="admin"></el-option>
            <el-option label="患者" value="patient"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="状态">
          <el-select
                  v-model="searchForm.status"
                  placeholder="请选择状态"
                  clearable
                  style="width: 120px"
          >
            <el-option label="启用" :value="1"></el-option>
            <el-option label="禁用" :value="0"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <i class="fas fa-search mr-1"></i> 搜索
          </el-button>
          <el-button @click="handleReset">
            <i class="fas fa-redo mr-1"></i> 重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 用户表格 -->
    <div class="table-container">
      <el-table
              :data="tableData"
              v-loading="loading"
              style="width: 100%"
              stripe
      >
        <el-table-column label="用户信息" width="200">
          <template #default="{ row }">
            <div style="display: flex; align-items: center;">
              <div class="user-avatar">
                {{ row.name ? row.name.charAt(0).toUpperCase() : 'U' }}
              </div>
              <div style="margin-left: 12px;">
                <div style="font-weight: 500;">{{ row.name || '-' }}</div>
                <div style="font-size: 12px; color: #909399;">ID: {{ row.id }}</div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="phone" label="手机号" width="140"></el-table-column>

        <el-table-column prop="email" label="邮箱" width="200">
          <template #default="{ row }">
            {{ row.email || '-' }}
          </template>
        </el-table-column>

        <el-table-column prop="role" label="角色" width="120">
          <template #default="{ row }">
            <el-tag :type="getRoleType(row.role)">
              {{ getRoleText(row.role) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="created" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
                    size="small"
                    @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
                    size="small"
                    type="danger"
                    @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
                v-model:current-page="pagination.current"
                v-model:page-size="pagination.size"
                :page-sizes="[3, 5,10, 20]"
                :total="pagination.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</div>

<script>
  // 配置Axios默认设置
  axios.defaults.baseURL = 'http://localhost:8080';
  axios.defaults.headers.post['Content-Type'] = 'application/json';
  axios.defaults.withCredentials = true;

  const { createApp, ref, reactive, onMounted } = Vue;
  const { ElMessage, ElMessageBox } = ElementPlus;

  createApp({
    setup() {
      // 所有变量定义必须在 return 之前

      // 编辑弹窗显示状态
      const dialogVisible = ref(false);

      // 编辑表单数据
      const editForm = reactive({
        id: '',
        name: '',
        phone: '',
        email: '',
        role: '',
        status: 1
      });

      // 编辑表单验证规则
      const editRules = reactive({
        name: [
          { required: true, message: '请输入用户姓名', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
        ],
        role: [
          { required: true, message: '请选择用户角色', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择账号状态', trigger: 'change' }
        ]
      });

      // 编辑表单引用
      const editFormRef = ref(null);

      // 搜索表单数据
      const searchForm = reactive({
        keyword: '',
        role: '',
        status: null
      });

      // 表格数据
      const tableData = ref([]);

      // 加载状态
      const loading = ref(false);

      // 分页数据
      const pagination = reactive({
        current: 1,
        size: 10,
        total: 0
      });

      // 获取角色显示文本
      const getRoleText = (role) => {
        const roleMap = {
          'doctor': '医生',
          'nurse': '护士',
          'admin': '管理员',
          'patient': '患者'
        };
        return roleMap[role] || role;
      };

      // 获取角色标签类型
      const getRoleType = (role) => {
        const typeMap = {
          'doctor': 'primary',
          'nurse': 'success',
          'admin': 'warning',
          'patient': 'info'
        };
        return typeMap[role] || 'info';
      };

      // 格式化日期
      const formatDate = (dateString) => {
        if (!dateString) return '-';
        try {
          const date = new Date(dateString);
          return date.toLocaleString('zh-CN');
        } catch (e) {
          return dateString;
        }
      };

      // 加载用户数据
      const loadUsers = async () => {
        loading.value = true;
        try {
          const params = {
            current: pagination.current,
            page: pagination.size,
            keyword: searchForm.keyword,
            role: searchForm.role,
            status: searchForm.status
          };

          const response = await axios.post('/user/selectByPage', params);
          const result = response.data;

          if (result.code === 200) {
            tableData.value = result.data.records;
            pagination.total = result.data.total;
          } else {
            ElMessage.error(result.msg || '加载用户数据失败');
          }
        } catch (error) {
          console.error('加载用户数据失败', error);
          ElMessage.error('加载用户数据失败，请检查网络连接');
        } finally {
          loading.value = false;
        }
      };

      // 搜索
      const handleSearch = () => {
        pagination.current = 1;
        loadUsers();
      };

      // 重置搜索
      const handleReset = () => {
        searchForm.keyword = '';
        searchForm.role = '';
        searchForm.status = null;
        pagination.current = 1;
        loadUsers();
      };

      // 刷新
      const handleRefresh = () => {
        loadUsers();
      };

      // 页大小改变
      const handleSizeChange = (size) => {
        pagination.size = size;
        pagination.current = 1;
        loadUsers();
      };

      // 当前页改变
      const handleCurrentChange = (current) => {
        pagination.current = current;
        loadUsers();
      };

      // 新增用户
      const handleAdd = () => {
        ElMessage.info('新增用户功能待实现');
      };

      // 编辑用户
      const handleEdit = async (row) => {
        try {
          dialogVisible.value = true;
          const response = await axios.get(`/user/${row.id}`);
          const result = response.data;

          if (result.code === 200) {
            const userData = result.data;
            editForm.id = userData.id;
            editForm.name = userData.name;
            editForm.phone = userData.phone;
            editForm.email = userData.email || '';
            editForm.role = userData.role;
            editForm.status = userData.status;
          } else {
            ElMessage.error('加载用户数据失败：' + result.msg);
            dialogVisible.value = false;
          }
        } catch (error) {
          console.error('编辑用户加载失败', error);
          ElMessage.error('加载用户数据失败，请重试');
          dialogVisible.value = false;
        }
      };

      // 提交更新用户数据
      const handleUpdateSubmit = async () => {
        const formRef = editFormRef.value;
        if (!formRef) return;

        try {
          await formRef.validate();
        } catch (error) {
          return;
        }

        try {
          const response = await axios.put(`/user/${editForm.id}`, editForm);
          const result = response.data;

          if (result.code === 200) {
            ElMessage.success('用户更新成功！');
            dialogVisible.value = false;
            loadUsers();
          } else {
            ElMessage.error('更新失败：' + (result.msg || '未知错误'));
          }
        } catch (error) {
          console.error('更新用户请求失败', error);
          ElMessage.error('更新失败，请检查网络或联系管理员');
        }
      };

      // 关闭弹窗时重置表单
      const handleDialogClose = () => {
        const formRef = editFormRef.value;
        if (formRef) {
          formRef.resetFields();
        }
        editForm.id = '';
        editForm.name = '';
        editForm.phone = '';
        editForm.email = '';
        editForm.role = '';
        editForm.status = 1;
      };

      // 删除用户
      const handleDelete = async (row) => {
        try {
          await ElMessageBox.confirm(
                  `确定要删除用户 "${row.name}" 吗？此操作不可恢复。`,
                  '确认删除',
                  {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                  }
          );

          const response = await axios.delete(`/user/${row.id}`);
          const result = response.data;

          if (result.code === 200) {
            ElMessage.success('删除成功');
            loadUsers();
          } else {
            ElMessage.error(result.msg || '删除失败');
          }
        } catch (error) {
          if (error !== 'cancel') {
            console.error('删除用户失败', error);
            ElMessage.error('删除失败，请重试');
          }
        }
      };

      // 页面加载时获取数据
      onMounted(() => {
        loadUsers();
      });

      // return 必须放在所有变量和函数定义之后
      return {
        searchForm,
        tableData,
        loading,
        pagination,
        dialogVisible,
        editForm,
        editRules,
        editFormRef,
        getRoleText,
        getRoleType,
        formatDate,
        handleSearch,
        handleReset,
        handleRefresh,
        handleSizeChange,
        handleCurrentChange,
        handleAdd,
        handleEdit,
        handleDelete,
        handleUpdateSubmit,
        handleDialogClose
      };
    }
  }).use(ElementPlus).mount('#app');
</script>
</body>
</html>